<?php
/**
 * Created by PhpStorm.
 * User: xunuo
 * Date: 2017/6/23
 * Time: 16:24
 */

namespace app\company\model;

use think\Validate;

/**
 * 用户模型
 * Class User
 * @package app\admin\model
 */
class User
{
    /**
     * 执行登录
     * @param $userName
     * @param $userPassword
     * @param $captcha
     */
    public function doLogin($userName, $userPassword, $captcha)
    {
        //验证
        $rule = [
            'username' => 'require',
            'password' => 'require',
            'captcha' => 'require|captcha',
        ];
        $data = [
            'username' => $userName,
            'password' => $userPassword,
            'captcha' => $captcha,
        ];
        $msg = [
            'username.require' => '用户名不能为空',
            'password.require' => '密码不能为空',
            'captcha.require' => '验证码不能为空',
            'captcha.captcha' => '验证码错误',
        ];
        $validate = new Validate($rule, $msg);
        if (!$validate->check($data)) {
            exception($validate->getError());
        }
        $user = db('users')
            ->where('username', $userName)
            ->where('password', sha1($userPassword))
            ->where('is_delete', 0)
            ->find();
        if (!$user) {
            exception('用户名或密码错误');
        }
        session('company', $user);
    }

    /**
     * 执行修改密码
     * @param $userId
     * @param $password
     * @param $newPassword
     */
    public function doModifyPassword($userId, $password, $newPassword)
    {
        $user = db('admin_user')
            ->where('id', $userId)
            ->where('user_password', sha1($password))
            ->find();
        if (!$user) {
            exception('密码错误');
        }
        $result = db('admin_user')
            ->where('id', $userId)
            ->update([
                'user_password' => sha1($newPassword),
            ]);
        if (!$result) {
            exception('修改失败');
        }
    }
}